import { error, JsonAsset } from "cc";
import loader from "./loader";
import { JAPI } from "./JAPI";

/** 数据缓存 */
var data: Map<string, any> = new Map();

export class JsonLoad {
    name:string;
    path:string;
    bundle?:string;
    isHttp?:boolean = false;
}

/** JSON数据表工具 */
export class JsonUtil {
    /**
     * 通知资源名从缓存中获取一个Json数据表
     * @param name  资源名
     */
    static get(name: string): any {
        if (data.has(name))
            return data.get(name);
    }
    
    /**
     * 获取所有Json
     */
    static getAll(){
        return data;
    }

    /**
     * 通知资源名加载Json数据表
     * @param name      资源名
     * @param callback  资源加载完成回调
     */
    static async load(load:JsonLoad, callback: Function = ()=>{}) {

        if (data.has(load.name)){
            callback(data.get(load.name));
            return data.get(load.name);
        }
        else {

            let json = null;
        
            if(load.isHttp){
                //加载Http请求
                let res = (await JAPI.get(load.path)).data;
                json = res;
            }else{
                //加载Json文件
                load.bundle = load.bundle || 'resources';
                let path = load.path+load.name;
                let res = await loader.loadlocal<JsonAsset>(path,load.bundle);
                json = res.json;
            }
            json && data.set(load.name, json);
            callback(json)
            return json;

        }
    }

    /**
     * 通过指定资源名释放资源
     * @param name 资源名
     */
    static release(load:JsonLoad) {
        data.delete(load.name);
        let path = load.path+load.name;
        loader.release(load.bundle,path);
    }

}
